﻿using System;
using System.Configuration;
using System.Web.Mvc;
using IndoReputation.Models.BusinessLogic;
using Telerik.Web.Mvc;
using IndoReputation.Views.ViewModels;
using IndoReputation.Models.BusinessObject;
using IndoReputation.Models.BusinessObject.Collections;
using IndoReputation.Commons;
using IndoReputation.Models.Constants;
using System.Web.Security;

namespace IndoReputation.Controllers
{    
    public class UsersController : BaseController
    {
        //
        // GET: /Users/

        [Authorize]
        public ActionResult Index()
        {
            return View();         
        }

        [Authorize]
        [GridAction]
        public ActionResult AjaxIndex()
        {
            return View(new GridModel(UsersBOL.GetAllUsersJoin()));
        }

        [HttpGet]
        public ActionResult Register()
        {
            var country = CountryBOL.GetAllCountry();
            var users = new UsersViewModel
            {
                Country = new SelectList(country, "ID", "Name")
            };
            return View(users);
        }

        [HttpPost]
        public ActionResult Register(UsersViewModel model)
        {
            if (ModelState.IsValid)
            {
                var users = new Users
                {
                    FullName = model.FullName.Trim(),
                    IsEnable = false,
                    LoginName = model.LoginName.Trim(),
                    MemoryWord = model.MemoryWord,
                    OfficeID = model.OfficeID,
                    Password = CommonFunctions.MD5Hash(model.Password),
                    Telephone = model.Telephone                    
                };
                UsersBOL.Insert(users);
            }
            return RedirectToAction("Index");
        }

        [HttpPost]
        public JsonResult AjaxGetDropDownListOffice(int? countryID)
        {
            var listOffice = new OfficeList();
            if (countryID.HasValue)
            {
                listOffice = OfficeBOL.GetAllOfficeByCountry((int) countryID);
            }
            return Json(new SelectList(listOffice, "ID", "Name"), JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult AjaxGetCountryROD(int? countryID)
        {
            var countryROD = new CountryROD();
            if (countryID.HasValue)
            {
                countryROD = CountryBOL.GetCountryRODById((int) countryID);
            }
            return Json(countryROD, JsonRequestBehavior.AllowGet);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [GridAction]
        public ActionResult AjaxDelete(int id)
        {
            //Find a customer with ProductID equal to the id action parameter            
            if (id > 0)
            {
                //Delete the record
                if (!UsersBOL.Delete(id))
                {
                    ModelState.AddModelError(String.Empty, @"This Users have Users CEO. Please check again!");
                }
            }
            //Rebind the grid
            return View(new GridModel(UsersBOL.GetAllUsersJoin()));
        }

        [Authorize]
        [HttpGet]
        public ActionResult SetPermission(int usersID)
        {
            var model = UsersBOL.GetUserCEOAndEnableById(usersID);            
            return View(model);
        }

        [Authorize]
        [HttpPost]
        public ActionResult SetPermission(UsersCheck model)
        {
            if (ModelState.IsValid)
            {
                var officeCEO = new OfficeCEOJoin {
                    IsCEO = model.IsCEO,
                    IsEnable = model.IsEnable,
                    IsEnableCEO = true,
                    Piority = Convert.ToInt16(model.Piority),
                    UserID = model.ID
                };
                OfficeCEOBOL.Update(officeCEO);
            }
            return RedirectToAction("Index");
        }

        [Authorize]
        [HttpGet]
        public ActionResult SetActiveAndAdmin(int usersID)
        {
            var user = UsersBOL.GetUserById(usersID);
            var model = new UserActive
                            {
                                FullName = user.FullName,
                                ID = user.ID,
                                IsAdmin = user.IsAdmin != null && (bool)user.IsAdmin,
                                IsEnable = user.IsEnable != null && (bool)user.IsEnable,
                                LoginName = user.LoginName
                            };
            return View(model);
        }

        [Authorize]
        [HttpPost]
        public ActionResult SetActiveAndAdmin(UserActive model)
        {
            if (ModelState.IsValid)
            {
                var user = new Users
                {
                    ID = model.ID,
                    IsAdmin = model.IsAdmin,
                    IsEnable = model.IsEnable
                };
                UsersBOL.UpdateActAdmin(user);
            }
            return RedirectToAction("Index");
        }

        [HttpGet]
        public ActionResult Login()
        {            
            return View();
        }

        [PopulateSiteMap(SiteMapName = "indositemap", ViewDataKey = "indositemap")]
        [HttpPost]
        public ActionResult Login(UserLoginViewModel model)
        {
            if (ModelState.IsValid)
            {
                IRConstants.UserStatus status = UsersBOL.GetUserByNameAndPass(model.LoginName.Trim(), CommonFunctions.MD5Hash(model.Password));
                switch (status)
                {
                    case IRConstants.UserStatus.Lock:
                        ModelState.AddModelError(string.Empty, "Your account has been lock, please confirm you administrator");
                        return View();                        
                    case IRConstants.UserStatus.NotExists:
                        ModelState.AddModelError(string.Empty, "Your password is incorrect or your account does not exists in our system");
                        return View();
                    case IRConstants.UserStatus.UnLock:
                        FormsAuthentication.SetAuthCookie(MySession.LoginName, true);
                        #region generate menu
                        if (!SiteMapManager.SiteMaps.ContainsKey("indositemap"))
                        {
                            if (MySession.IsAdmin)
                            {
                                SiteMapManager.SiteMaps.Register<XmlSiteMap>("indositemap", sitmap => sitmap.LoadFrom("~/Web.sitemap"));
                            }
                            else
                            {
                                SiteMapManager.SiteMaps.Register<XmlSiteMap>("indositemap", sitmap => sitmap.LoadFrom("~/Member.sitemap"));
                            }

                        }
                        else
                        {
                            SiteMapManager.SiteMaps.Clear();
                            if (MySession.IsAdmin)
                            {
                                SiteMapManager.SiteMaps.Register<XmlSiteMap>("indositemap", sitmap => sitmap.LoadFrom("~/Web.sitemap"));
                            }
                            else
                            {
                                SiteMapManager.SiteMaps.Register<XmlSiteMap>("indositemap", sitmap => sitmap.LoadFrom("~/Member.sitemap"));
                            }
                        }
                        #endregion
                        var returnUrl = Request.QueryString["ReturnUrl"];
                        if (!string.IsNullOrEmpty(returnUrl))
                        {
                            return Redirect(returnUrl);
                        }
                        return RedirectToAction("Index", "Home");
                }
            }
            return RedirectToAction("Index");
        }

        [HttpGet]
        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();
            Session.Clear();
            return RedirectToAction("Index", "Home");
        }

        public JsonResult EmailAddressUsed(string loginName)
        {
            return !UsersBOL.CheckDuplicateLoginName(loginName) ? Json(loginName + " is already in use.", JsonRequestBehavior.AllowGet) : Json(true, JsonRequestBehavior.AllowGet);
        }

        public ActionResult ForgotPassword()
        {
            return View();
        }

        [HttpPost]
        public JsonResult AjaxSendEmailAdministrator(string content)
        {
            var listUserAdmin = UsersBOL.GetAllUsersAdmin();
            return listUserAdmin != null ? Json(listUserAdmin.Count > 0 && CommonFunctions.SendEmail("Forgot password", content, ConfigurationManager.AppSettings["SystemEmail"], listUserAdmin[0].LoginName), JsonRequestBehavior.AllowGet) : Json(false, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult AjaxResetPassAndSendEmailUser(string email, string memoryword)
        {
            var users = UsersBOL.GetUserByNameAndWord(email, memoryword);
            if(users != null)
            {
                var newPass = CommonFunctions.GetRandomString();
                users.Password = CommonFunctions.MD5Hash(newPass);
                var content = "Your new passwrod in Indoreputation is: " + newPass;
                if (UsersBOL.Update(users))
                    return
                        Json(
                            CommonFunctions.SendEmail("Forgot password", content,
                                                      ConfigurationManager.AppSettings["SystemEmail"], users.LoginName),
                            JsonRequestBehavior.AllowGet);
                return Json(false, JsonRequestBehavior.AllowGet);
            }
            return Json(false, JsonRequestBehavior.AllowGet);
        }
    }
}
